home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1993 July / InfoMagic USENET CD-ROM July 1993.ISO / sources / unix / volume17 / gnugrep / part04 < prev    next >
Encoding:
Internet Message Format  |  1989-02-08  |  56.6 KB

  1. Subject:  v17i101:  Gnu E?GREP (it's fast), Part04/05
  2. Newsgroups: comp.sources.unix
  3. Sender: sources
  4. Approved: rsalz@uunet.UU.NET
  5.  
  6. Submitted-by: Mike Haertel <mike@wheaties.ai.mit.edu>
  7. Posting-number: Volume 17, Issue 101
  8. Archive-name: gnugrep/part04
  9.  
  10. #! /bin/sh
  11. # This is a shell archive.  Remove anything before this line, then unpack
  12. # it by saving it into a file and typing "sh file".  To overwrite existing
  13. # files, type "sh file -c".  You can also feed this as standard input via
  14. # unshar, or by typing "sh <file", e.g..  If this archive is complete, you
  15. # will see the following message at the end:
  16. #        "End of shell archive."
  17. # Contents:  dfa.c
  18. PATH=/bin:/usr/bin:/usr/ucb ; export PATH
  19. if test -f 'dfa.c' -a "${1}" != "-c" ; then 
  20.   echo shar: Will not clobber existing file \"'dfa.c'\"
  21. else
  22. echo shar: Extracting \"'dfa.c'\" \(54865 characters\)
  23. sed "s/^X//" >'dfa.c' <<'END_OF_FILE'
  24. X/* dfa.c - determinisitic extended regexp routines for GNU
  25. X   Copyright (C) 1988 Free Software Foundation, Inc.
  26. X                      Written June, 1988 by Mike Haertel
  27. X              Modified July, 1988 by Arthur David Olson
  28. X             to assist BMG speedups
  29. X
  30. X               NO WARRANTY
  31. X
  32. X  BECAUSE THIS PROGRAM IS LICENSED FREE OF CHARGE, WE PROVIDE ABSOLUTELY
  33. XNO WARRANTY, TO THE EXTENT PERMITTED BY APPLICABLE STATE LAW.  EXCEPT
  34. XWHEN OTHERWISE STATED IN WRITING, FREE SOFTWARE FOUNDATION, INC,
  35. XRICHARD M. STALLMAN AND/OR OTHER PARTIES PROVIDE THIS PROGRAM "AS IS"
  36. XWITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
  37. XBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  38. XFITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY
  39. XAND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE PROGRAM PROVE
  40. XDEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
  41. XCORRECTION.
  42. X
  43. X IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW WILL RICHARD M.
  44. XSTALLMAN, THE FREE SOFTWARE FOUNDATION, INC., AND/OR ANY OTHER PARTY
  45. XWHO MAY MODIFY AND REDISTRIBUTE THIS PROGRAM AS PERMITTED BELOW, BE
  46. XLIABLE TO YOU FOR DAMAGES, INCLUDING ANY LOST PROFITS, LOST MONIES, OR
  47. XOTHER SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
  48. XUSE OR INABILITY TO USE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR
  49. XDATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY THIRD PARTIES OR
  50. XA FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS) THIS
  51. XPROGRAM, EVEN IF YOU HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
  52. XDAMAGES, OR FOR ANY CLAIM BY ANY OTHER PARTY.
  53. X
  54. X        GENERAL PUBLIC LICENSE TO COPY
  55. X
  56. X  1. You may copy and distribute verbatim copies of this source file
  57. Xas you receive it, in any medium, provided that you conspicuously and
  58. Xappropriately publish on each copy a valid copyright notice "Copyright
  59. X (C) 1988 Free Software Foundation, Inc."; and include following the
  60. Xcopyright notice a verbatim copy of the above disclaimer of warranty
  61. Xand of this License.  You may charge a distribution fee for the
  62. Xphysical act of transferring a copy.
  63. X
  64. X  2. You may modify your copy or copies of this source file or
  65. Xany portion of it, and copy and distribute such modifications under
  66. Xthe terms of Paragraph 1 above, provided that you also do the following:
  67. X
  68. X    a) cause the modified files to carry prominent notices stating
  69. X    that you changed the files and the date of any change; and
  70. X
  71. X    b) cause the whole of any work that you distribute or publish,
  72. X    that in whole or in part contains or is a derivative of this
  73. X    program or any part thereof, to be licensed at no charge to all
  74. X    third parties on terms identical to those contained in this
  75. X    License Agreement (except that you may choose to grant more extensive
  76. X    warranty protection to some or all third parties, at your option).
  77. X
  78. X    c) You may charge a distribution fee for the physical act of
  79. X    transferring a copy, and you may at your option offer warranty
  80. X    protection in exchange for a fee.
  81. X
  82. XMere aggregation of another unrelated program with this program (or its
  83. Xderivative) on a volume of a storage or distribution medium does not bring
  84. Xthe other program under the scope of these terms.
  85. X
  86. X  3. You may copy and distribute this program or any portion of it in
  87. Xcompiled, executable or object code form under the terms of Paragraphs
  88. X1 and 2 above provided that you do the following:
  89. X
  90. X    a) accompany it with the complete corresponding machine-readable
  91. X    source code, which must be distributed under the terms of
  92. X    Paragraphs 1 and 2 above; or,
  93. X
  94. X    b) accompany it with a written offer, valid for at least three
  95. X    years, to give any third party free (except for a nominal
  96. X    shipping charge) a complete machine-readable copy of the
  97. X    corresponding source code, to be distributed under the terms of
  98. X    Paragraphs 1 and 2 above; or,
  99. X
  100. X    c) accompany it with the information you received as to where the
  101. X    corresponding source code may be obtained.  (This alternative is
  102. X    allowed only for noncommercial distribution and only if you
  103. X    received the program in object code or executable form alone.)
  104. X
  105. XFor an executable file, complete source code means all the source code for
  106. Xall modules it contains; but, as a special exception, it need not include
  107. Xsource code for modules which are standard libraries that accompany the
  108. Xoperating system on which the executable file runs.
  109. X
  110. X  4. You may not copy, sublicense, distribute or transfer this program
  111. Xexcept as expressly provided under this License Agreement.  Any attempt
  112. Xotherwise to copy, sublicense, distribute or transfer this program is void and
  113. Xyour rights to use the program under this License agreement shall be
  114. Xautomatically terminated.  However, parties who have received computer
  115. Xsoftware programs from you with this License Agreement will not have
  116. Xtheir licenses terminated so long as such parties remain in full compliance.
  117. X
  118. X  5. If you wish to incorporate parts of this program into other free
  119. Xprograms whose distribution conditions are different, write to the Free
  120. XSoftware Foundation at 675 Mass Ave, Cambridge, MA 02139.  We have not yet
  121. Xworked out a simple rule that can be stated here, but we will often permit
  122. Xthis.  We will be guided by the two goals of preserving the free status of
  123. Xall derivatives our free software and of promoting the sharing and reuse of
  124. Xsoftware.
  125. X
  126. X
  127. XIn other words, you are welcome to use, share and improve this program.
  128. XYou are forbidden to forbid anyone else to use, share and improve
  129. Xwhat you give them.   Help stamp out software-hoarding!  */
  130. X
  131. X#include <ctype.h>
  132. X#include "dfa.h"
  133. X
  134. X#ifdef __STDC__
  135. Xtypedef void *ptr_t;
  136. X#else
  137. Xtypedef char *ptr_t;
  138. X#endif
  139. X
  140. Xstatic void    regmust();
  141. X
  142. Xstatic ptr_t
  143. Xxcalloc(n, s)
  144. X     int n;
  145. X     size_t s;
  146. X{
  147. X  ptr_t r = calloc(n, s);
  148. X
  149. X  if (r)
  150. X    return r;
  151. X  else
  152. X    regerror("Memory exhausted");
  153. X}
  154. X
  155. Xstatic ptr_t
  156. Xxmalloc(n)
  157. X     size_t n;
  158. X{
  159. X  ptr_t r = malloc(n);
  160. X
  161. X  if (r)
  162. X    return r;
  163. X  else
  164. X    regerror("Memory exhausted");
  165. X}
  166. X
  167. Xstatic ptr_t
  168. Xxrealloc(p, n)
  169. X     ptr_t p;
  170. X     size_t n;
  171. X{
  172. X  ptr_t r = realloc(p, n);
  173. X
  174. X  if (r)
  175. X    return r;
  176. X  else
  177. X    regerror("Memory exhausted");
  178. X}
  179. X
  180. X#define CALLOC(p, t, n) ((p) = (t *) xcalloc((n), sizeof (t)))
  181. X#define MALLOC(p, t, n) ((p) = (t *) xmalloc((n) * sizeof (t)))
  182. X#define REALLOC(p, t, n) ((p) = (t *) xrealloc((ptr_t) (p), (n) * sizeof (t)))
  183. X
  184. X/* Reallocate an array of type t if nalloc is too small for index. */
  185. X#define REALLOC_IF_NECESSARY(p, t, nalloc, index) \
  186. X  if ((index) >= (nalloc))              \
  187. X    {                          \
  188. X      while ((index) >= (nalloc))          \
  189. X    (nalloc) *= 2;                  \
  190. X      REALLOC(p, t, nalloc);              \
  191. X    }
  192. X
  193. X/* Stuff pertaining to charsets. */
  194. X
  195. Xstatic
  196. Xtstbit(b, c)
  197. X     int b;
  198. X     _charset c;
  199. X{
  200. X  return c[b / INTBITS] & 1 << b % INTBITS;
  201. X}
  202. X
  203. Xstatic void
  204. Xsetbit(b, c)
  205. X     int b;
  206. X     _charset c;
  207. X{
  208. X  c[b / INTBITS] |= 1 << b % INTBITS;
  209. X}
  210. X
  211. Xstatic void
  212. Xclrbit(b, c)
  213. X     int b;
  214. X     _charset c;
  215. X{
  216. X  c[b / INTBITS] &= ~(1 << b % INTBITS);
  217. X}
  218. X
  219. Xstatic void
  220. Xcopyset(src, dst)
  221. X     const _charset src;
  222. X     _charset dst;
  223. X{
  224. X  int i;
  225. X
  226. X  for (i = 0; i < _CHARSET_INTS; ++i)
  227. X    dst[i] = src[i];
  228. X}
  229. X
  230. Xstatic void
  231. Xzeroset(s)
  232. X     _charset s;
  233. X{
  234. X  int i;
  235. X
  236. X  for (i = 0; i < _CHARSET_INTS; ++i)
  237. X    s[i] = 0;
  238. X}
  239. X
  240. Xstatic void
  241. Xnotset(s)
  242. X     _charset s;
  243. X{
  244. X  int i;
  245. X
  246. X  for (i = 0; i < _CHARSET_INTS; ++i)
  247. X    s[i] = ~s[i];
  248. X}
  249. X
  250. Xstatic
  251. Xequal(s1, s2)
  252. X     const _charset s1;
  253. X     const _charset s2;
  254. X{
  255. X  int i;
  256. X
  257. X  for (i = 0; i < _CHARSET_INTS; ++i)
  258. X    if (s1[i] != s2[i])
  259. X      return 0;
  260. X  return 1;
  261. X}
  262. X
  263. X/* A pointer to the current regexp is kept here during parsing. */
  264. Xstatic struct regexp *reg;
  265. X
  266. X/* Find the index of charset s in reg->charsets, or allocate a new charset. */
  267. Xstatic
  268. Xcharset_index(s)
  269. X     const _charset s;
  270. X{
  271. X  int i;
  272. X
  273. X  for (i = 0; i < reg->cindex; ++i)
  274. X    if (equal(s, reg->charsets[i]))
  275. X      return i;
  276. X  REALLOC_IF_NECESSARY(reg->charsets, _charset, reg->calloc, reg->cindex);
  277. X  ++reg->cindex;
  278. X  copyset(s, reg->charsets[i]);
  279. X  return i;
  280. X}
  281. X
  282. X/* Syntax bits controlling the behavior of the lexical analyzer. */
  283. Xstatic syntax_bits, syntax_bits_set;
  284. X
  285. X/* Flag for case-folding letters into sets. */
  286. Xstatic case_fold;
  287. X
  288. X/* Entry point to set syntax options. */
  289. Xvoid
  290. Xregsyntax(bits, fold)
  291. X     int bits;
  292. X     int fold;
  293. X{
  294. X  syntax_bits_set = 1;
  295. X  syntax_bits = bits;
  296. X  case_fold = fold;
  297. X}
  298. X
  299. X/* Lexical analyzer. */
  300. Xstatic const char *lexstart;    /* Pointer to beginning of input string. */
  301. Xstatic const char *lexptr;    /* Pointer to next input character. */
  302. Xstatic lexleft;            /* Number of characters remaining. */
  303. Xstatic caret_allowed;        /* True if backward context allows ^
  304. X                   (meaningful only if RE_CONTEXT_INDEP_OPS
  305. X                   is turned off). */
  306. Xstatic closure_allowed;        /* True if backward context allows closures
  307. X                   (meaningful only if RE_CONTEXT_INDEP_OPS
  308. X                   is turned off). */
  309. X
  310. X/* Note that characters become unsigned here. */
  311. X#define FETCH(c, eoferr)             \
  312. X  {                         \
  313. X    if (! lexleft)                 \
  314. X      if (eoferr)                 \
  315. X    regerror(eoferr);            \
  316. X      else                     \
  317. X    return _END;                 \
  318. X    (c) = (unsigned char) *lexptr++;  \
  319. X    --lexleft;                     \
  320. X  }
  321. X
  322. Xstatic _token
  323. Xlex()
  324. X{
  325. X  _token c, c2;
  326. X  int invert;
  327. X  _charset cset;
  328. X
  329. X  FETCH(c, (char *) 0);
  330. X  switch (c)
  331. X    {
  332. X    case '^':
  333. X      if (! (syntax_bits & RE_CONTEXT_INDEP_OPS)
  334. X      && (!caret_allowed ||
  335. X          (syntax_bits & RE_TIGHT_VBAR) && lexptr - 1 != lexstart))
  336. X    goto normal_char;
  337. X      caret_allowed = 0;
  338. X      return syntax_bits & RE_TIGHT_VBAR ? _ALLBEGLINE : _BEGLINE;
  339. X
  340. X    case '$':
  341. X      if (syntax_bits & RE_CONTEXT_INDEP_OPS || !lexleft
  342. X      || (! (syntax_bits & RE_TIGHT_VBAR)
  343. X          && ((syntax_bits & RE_NO_BK_PARENS
  344. X           ? lexleft > 0 && *lexptr == ')'
  345. X           : lexleft > 1 && *lexptr == '\\' && lexptr[1] == ')')
  346. X          || (syntax_bits & RE_NO_BK_VBAR
  347. X              ? lexleft > 0 && *lexptr == '|'
  348. X              : lexleft > 1 && *lexptr == '\\' && lexptr[1] == '|'))))
  349. X    return syntax_bits & RE_TIGHT_VBAR ? _ALLENDLINE : _ENDLINE;
  350. X      goto normal_char;
  351. X
  352. X    case '\\':
  353. X      FETCH(c, "Unfinished \\ quote");
  354. X      switch (c)
  355. X    {
  356. X    case '1':
  357. X    case '2':
  358. X    case '3':
  359. X    case '4':
  360. X    case '5':
  361. X    case '6':
  362. X    case '7':
  363. X    case '8':
  364. X    case '9':
  365. X      caret_allowed = 0;
  366. X      closure_allowed = 1;
  367. X      return _BACKREF;
  368. X
  369. X    case '<':
  370. X      caret_allowed = 0;
  371. X      return _BEGWORD;
  372. X
  373. X    case '>':
  374. X      caret_allowed = 0;
  375. X      return _ENDWORD;
  376. X
  377. X    case 'b':
  378. X      caret_allowed = 0;
  379. X      return _LIMWORD;
  380. X
  381. X    case 'B':
  382. X      caret_allowed = 0;
  383. X      return _NOTLIMWORD;
  384. X
  385. X    case 'w':
  386. X    case 'W':
  387. X      zeroset(cset);
  388. X      for (c2 = 0; c2 < _NOTCHAR; ++c2)
  389. X        if (ISALNUM(c2))
  390. X          setbit(c2, cset);
  391. X      if (c == 'W')
  392. X        notset(cset);
  393. X      caret_allowed = 0;
  394. X      closure_allowed = 1;
  395. X      return _SET + charset_index(cset);
  396. X
  397. X    case '?':
  398. X      if (syntax_bits & RE_BK_PLUS_QM)
  399. X        goto qmark;
  400. X      goto normal_char;
  401. X
  402. X    case '+':
  403. X      if (syntax_bits & RE_BK_PLUS_QM)
  404. X        goto plus;
  405. X      goto normal_char;
  406. X
  407. X    case '|':
  408. X      if (! (syntax_bits & RE_NO_BK_VBAR))
  409. X        goto or;
  410. X      goto normal_char;
  411. X
  412. X    case '(':
  413. X      if (! (syntax_bits & RE_NO_BK_PARENS))
  414. X        goto lparen;
  415. X      goto normal_char;
  416. X
  417. X    case ')':
  418. X      if (! (syntax_bits & RE_NO_BK_PARENS))
  419. X        goto rparen;
  420. X      goto normal_char;
  421. X
  422. X    default:
  423. X      goto normal_char;
  424. X    }
  425. X
  426. X    case '?':
  427. X      if (syntax_bits & RE_BK_PLUS_QM)
  428. X    goto normal_char;
  429. X    qmark:
  430. X      if (! (syntax_bits & RE_CONTEXT_INDEP_OPS) && !closure_allowed)
  431. X    goto normal_char;
  432. X      return _QMARK;
  433. X
  434. X    case '*':
  435. X      if (! (syntax_bits & RE_CONTEXT_INDEP_OPS) && !closure_allowed)
  436. X    goto normal_char;
  437. X      return _STAR;
  438. X
  439. X    case '+':
  440. X      if (syntax_bits & RE_BK_PLUS_QM)
  441. X    goto normal_char;
  442. X    plus:
  443. X      if (! (syntax_bits & RE_CONTEXT_INDEP_OPS) && !closure_allowed)
  444. X    goto normal_char;
  445. X      return _PLUS;
  446. X
  447. X    case '|':
  448. X      if (! (syntax_bits & RE_NO_BK_VBAR))
  449. X    goto normal_char;
  450. X    or:
  451. X      caret_allowed = 1;
  452. X      closure_allowed = 0;
  453. X      return _OR;
  454. X
  455. X    case '\n':
  456. X      if (! (syntax_bits & RE_NEWLINE_OR))
  457. X    goto normal_char;
  458. X      goto or;
  459. X
  460. X    case '(':
  461. X      if (! (syntax_bits & RE_NO_BK_PARENS))
  462. X    goto normal_char;
  463. X    lparen:
  464. X      caret_allowed = 1;
  465. X      closure_allowed = 0;
  466. X      return _LPAREN;
  467. X
  468. X    case ')':
  469. X      if (! (syntax_bits & RE_NO_BK_PARENS))
  470. X    goto normal_char;
  471. X    rparen:
  472. X      caret_allowed = 0;
  473. X      closure_allowed = 1;
  474. X      return _RPAREN;
  475. X
  476. X    case '.':
  477. X      zeroset(cset);
  478. X      notset(cset);
  479. X      clrbit('\n', cset);
  480. X      caret_allowed = 0;
  481. X      closure_allowed = 1;
  482. X      return _SET + charset_index(cset);
  483. X
  484. X    case '[':
  485. X      zeroset(cset);
  486. X      FETCH(c, "Unbalanced [");
  487. X      if (c == '^')
  488. X    {
  489. X      FETCH(c, "Unbalanced [");
  490. X      invert = 1;
  491. X    }
  492. X      else
  493. X    invert = 0;
  494. X      do
  495. X    {
  496. X      FETCH(c2, "Unbalanced [");
  497. X      if (c2 == '-')
  498. X        {
  499. X          FETCH(c2, "Unbalanced [");
  500. X          while (c <= c2)
  501. X          setbit(c++, cset);
  502. X          FETCH(c, "Unbalanced [");
  503. X        }
  504. X      else
  505. X        {
  506. X          setbit(c, cset);
  507. X          c = c2;
  508. X        }
  509. X    }
  510. X      while (c != ']');
  511. X      if (invert)
  512. X    notset(cset);
  513. X      caret_allowed = 0;
  514. X      closure_allowed = 1;
  515. X      return _SET + charset_index(cset);
  516. X
  517. X    default:
  518. X    normal_char:
  519. X      caret_allowed = 0;
  520. X      closure_allowed = 1;
  521. X      if (case_fold && ISALPHA(c))
  522. X    {
  523. X      zeroset(cset);
  524. X      if (isupper(c))
  525. X        c = tolower(c);
  526. X      setbit(c, cset);
  527. X      setbit(toupper(c), cset);
  528. X      return _SET + charset_index(cset);
  529. X    }
  530. X      return c;
  531. X    }
  532. X}
  533. X
  534. X/* Recursive descent parser for regular expressions. */
  535. X
  536. Xstatic _token tok;        /* Lookahead token. */
  537. Xstatic depth;            /* Current depth of a hypothetical stack
  538. X                   holding deferred productions.  This is
  539. X                   used to determine the depth that will be
  540. X                   required of the real stack later on in
  541. X                   reganalyze(). */
  542. X
  543. X/* Add the given token to the parse tree, maintaining the depth count and
  544. X   updating the maximum depth if necessary. */
  545. Xstatic void
  546. Xaddtok(t)
  547. X     _token t;
  548. X{
  549. X  REALLOC_IF_NECESSARY(reg->tokens, _token, reg->talloc, reg->tindex);
  550. X  reg->tokens[reg->tindex++] = t;
  551. X
  552. X  switch (t)
  553. X    {
  554. X    case _QMARK:
  555. X    case _STAR:
  556. X    case _PLUS:
  557. X      break;
  558. X
  559. X    case _CAT:
  560. X    case _OR:
  561. X      --depth;
  562. X      break;
  563. X
  564. X    default:
  565. X      ++reg->nleaves;
  566. X    case _EMPTY:
  567. X      ++depth;
  568. X      break;
  569. X    }
  570. X  if (depth > reg->depth)
  571. X    reg->depth = depth;
  572. X}
  573. X
  574. X/* The grammar understood by the parser is as follows.
  575. X
  576. X   start:
  577. X     regexp
  578. X     _ALLBEGLINE regexp
  579. X     regexp _ALLENDLINE
  580. X     _ALLBEGLINE regexp _ALLENDLINE
  581. X
  582. X   regexp:
  583. X     regexp _OR branch
  584. X     branch
  585. X
  586. X   branch:
  587. X     branch closure
  588. X     closure
  589. X
  590. X   closure:
  591. X     closure _QMARK
  592. X     closure _STAR
  593. X     closure _PLUS
  594. X     atom
  595. X
  596. X   atom:
  597. X     <normal character>
  598. X     _SET
  599. X     _BACKREF
  600. X     _BEGLINE
  601. X     _ENDLINE
  602. X     _BEGWORD
  603. X     _ENDWORD
  604. X     _LIMWORD
  605. X     _NOTLIMWORD
  606. X     <empty>
  607. X
  608. X   The parser builds a parse tree in postfix form in an array of tokens. */
  609. X
  610. X#ifdef __STDC__
  611. Xstatic void regexp(void);
  612. X#else
  613. Xstatic void regexp();
  614. X#endif
  615. X
  616. Xstatic void
  617. Xatom()
  618. X{
  619. X  if (tok >= 0 && tok < _NOTCHAR || tok >= _SET || tok == _BACKREF
  620. X      || tok == _BEGLINE || tok == _ENDLINE || tok == _BEGWORD
  621. X      || tok == _ENDWORD || tok == _LIMWORD || tok == _NOTLIMWORD)
  622. X    {
  623. X      addtok(tok);
  624. X      tok = lex();
  625. X    }
  626. X  else if (tok == _LPAREN)
  627. X    {
  628. X      tok = lex();
  629. X      regexp();
  630. X      if (tok != _RPAREN)
  631. X    regerror("Unbalanced (");
  632. X      tok = lex();
  633. X    }
  634. X  else
  635. X    addtok(_EMPTY);
  636. X}
  637. X
  638. Xstatic void
  639. Xclosure()
  640. X{
  641. X  atom();
  642. X  while (tok == _QMARK || tok == _STAR || tok == _PLUS)
  643. X    {
  644. X      addtok(tok);
  645. X      tok = lex();
  646. X    }
  647. X}
  648. X
  649. Xstatic void
  650. Xbranch()
  651. X{
  652. X  closure();
  653. X  while (tok != _RPAREN && tok != _OR && tok != _ALLENDLINE && tok >= 0)
  654. X    {
  655. X      closure();
  656. X      addtok(_CAT);
  657. X    }
  658. X}
  659. X
  660. Xstatic void
  661. Xregexp()
  662. X{
  663. X  branch();
  664. X  while (tok == _OR)
  665. X    {
  666. X      tok = lex();
  667. X      branch();
  668. X      addtok(_OR);
  669. X    }
  670. X}
  671. X
  672. X/* Main entry point for the parser.  S is a string to be parsed, len is the
  673. X   length of the string, so s can include NUL characters.  R is a pointer to
  674. X   the struct regexp to parse into. */
  675. Xvoid
  676. Xregparse(s, len, r)
  677. X     const char *s;
  678. X     size_t len;
  679. X     struct regexp *r;
  680. X{
  681. X  reg = r;
  682. X  lexstart = lexptr = s;
  683. X  lexleft = len;
  684. X  caret_allowed = 1;
  685. X  closure_allowed = 0;
  686. X
  687. X  if (! syntax_bits_set)
  688. X    regerror("No syntax specified");
  689. X
  690. X  tok = lex();
  691. X  depth = r->depth;
  692. X
  693. X  if (tok == _ALLBEGLINE)
  694. X    {
  695. X      addtok(_BEGLINE);
  696. X      tok = lex();
  697. X      regexp();
  698. X      addtok(_CAT);
  699. X    }
  700. X  else
  701. X    regexp();
  702. X
  703. X  if (tok == _ALLENDLINE)
  704. X    {
  705. X      addtok(_ENDLINE);
  706. X      addtok(_CAT);
  707. X      tok = lex();
  708. X    }
  709. X
  710. X  if (tok != _END)
  711. X    regerror("Unbalanced )");
  712. X
  713. X  addtok(_END - r->nregexps);
  714. X  addtok(_CAT);
  715. X
  716. X  if (r->nregexps)
  717. X    addtok(_OR);
  718. X
  719. X  ++r->nregexps;
  720. X}
  721. X
  722. X/* Some primitives for operating on sets of positions. */
  723. X
  724. X/* Copy one set to another; the destination must be large enough. */
  725. Xstatic void
  726. Xcopy(src, dst)
  727. X     const _position_set *src;
  728. X     _position_set *dst;
  729. X{
  730. X  int i;
  731. X
  732. X  for (i = 0; i < src->nelem; ++i)
  733. X    dst->elems[i] = src->elems[i];
  734. X  dst->nelem = src->nelem;
  735. X}
  736. X
  737. X/* Insert a position in a set.  Position sets are maintained in sorted
  738. X   order according to index.  If position already exists in the set with
  739. X   the same index then their constraints are logically or'd together.
  740. X   S->elems must point to an array large enough to hold the resulting set. */
  741. Xstatic void
  742. Xinsert(p, s)
  743. X     _position p;
  744. X     _position_set *s;
  745. X{
  746. X  int i;
  747. X  _position t1, t2;
  748. X
  749. X  for (i = 0; i < s->nelem && p.index < s->elems[i].index; ++i)
  750. X    ;
  751. X  if (i < s->nelem && p.index == s->elems[i].index)
  752. X    s->elems[i].constraint |= p.constraint;
  753. X  else
  754. X    {
  755. X      t1 = p;
  756. X      ++s->nelem;
  757. X      while (i < s->nelem)
  758. X    {
  759. X      t2 = s->elems[i];
  760. X      s->elems[i++] = t1;
  761. X      t1 = t2;
  762. X    }
  763. X    }
  764. X}
  765. X
  766. X/* Merge two sets of positions into a third.  The result is exactly as if
  767. X   the positions of both sets were inserted into an initially empty set. */
  768. Xstatic void
  769. Xmerge(s1, s2, m)
  770. X     _position_set *s1;
  771. X     _position_set *s2;
  772. X     _position_set *m;
  773. X{
  774. X  int i = 0, j = 0;
  775. X
  776. X  m->nelem = 0;
  777. X  while (i < s1->nelem && j < s2->nelem)
  778. X    if (s1->elems[i].index > s2->elems[j].index)
  779. X      m->elems[m->nelem++] = s1->elems[i++];
  780. X    else if (s1->elems[i].index < s2->elems[j].index)
  781. X      m->elems[m->nelem++] = s2->elems[j++];
  782. X    else
  783. X      {
  784. X    m->elems[m->nelem] = s1->elems[i++];
  785. X    m->elems[m->nelem++].constraint |= s2->elems[j++].constraint;
  786. X      }
  787. X  while (i < s1->nelem)
  788. X    m->elems[m->nelem++] = s1->elems[i++];
  789. X  while (j < s2->nelem)
  790. X    m->elems[m->nelem++] = s2->elems[j++];
  791. X}
  792. X
  793. X/* Delete a position from a set. */
  794. Xstatic void
  795. Xdelete(p, s)
  796. X     _position p;
  797. X     _position_set *s;
  798. X{
  799. X  int i;
  800. X
  801. X  for (i = 0; i < s->nelem; ++i)
  802. X    if (p.index == s->elems[i].index)
  803. X      break;
  804. X  if (i < s->nelem)
  805. X    for (--s->nelem; i < s->nelem; ++i)
  806. X      s->elems[i] = s->elems[i + 1];
  807. X}
  808. X
  809. X/* Find the index of the state corresponding to the given position set with
  810. X   the given preceding context, or create a new state if there is no such
  811. X   state.  Newline and letter tell whether we got here on a newline or
  812. X   letter, respectively. */
  813. Xstatic
  814. Xstate_index(r, s, newline, letter)
  815. X     struct regexp *r;
  816. X     _position_set *s;
  817. X     int newline;
  818. X     int letter;
  819. X{
  820. X  int hash = 0;
  821. X  int constraint;
  822. X  int i, j;
  823. X
  824. X  newline = newline ? 1 : 0;
  825. X  letter = letter ? 1 : 0;
  826. X
  827. X  for (i = 0; i < s->nelem; ++i)
  828. X    hash ^= s->elems[i].index + s->elems[i].constraint;
  829. X
  830. X  /* Try to find a state that exactly matches the proposed one. */
  831. X  for (i = 0; i < r->sindex; ++i)
  832. X    {
  833. X      if (hash != r->states[i].hash || s->nelem != r->states[i].elems.nelem
  834. X      || newline != r->states[i].newline || letter != r->states[i].letter)
  835. X    continue;
  836. X      for (j = 0; j < s->nelem; ++j)
  837. X    if (s->elems[j].constraint
  838. X        != r->states[i].elems.elems[j].constraint
  839. X        || s->elems[j].index != r->states[i].elems.elems[j].index)
  840. X      break;
  841. X      if (j == s->nelem)
  842. X    return i;
  843. X    }
  844. X
  845. X  /* We'll have to create a new state. */
  846. X  REALLOC_IF_NECESSARY(r->states, _dfa_state, r->salloc, r->sindex);
  847. X  r->states[i].hash = hash;
  848. X  MALLOC(r->states[i].elems.elems, _position, s->nelem);
  849. X  copy(s, &r->states[i].elems);
  850. X  r->states[i].newline = newline;
  851. X  r->states[i].letter = letter;
  852. X  r->states[i].backref = 0;
  853. X  r->states[i].constraint = 0;
  854. X  r->states[i].first_end = 0;
  855. X  for (j = 0; j < s->nelem; ++j)
  856. X    if (r->tokens[s->elems[j].index] < 0)
  857. X      {
  858. X    constraint = s->elems[j].constraint;
  859. X    if (_SUCCEEDS_IN_CONTEXT(constraint, newline, 0, letter, 0)
  860. X        || _SUCCEEDS_IN_CONTEXT(constraint, newline, 0, letter, 1)
  861. X        || _SUCCEEDS_IN_CONTEXT(constraint, newline, 1, letter, 0)
  862. X        || _SUCCEEDS_IN_CONTEXT(constraint, newline, 1, letter, 1))
  863. X      r->states[i].constraint |= constraint;
  864. X    if (! r->states[i].first_end)
  865. X      r->states[i].first_end = r->tokens[s->elems[j].index];
  866. X      }
  867. X    else if (r->tokens[s->elems[j].index] == _BACKREF)
  868. X      {
  869. X    r->states[i].constraint = _NO_CONSTRAINT;
  870. X    r->states[i].backref = 1;
  871. X      }
  872. X
  873. X  ++r->sindex;
  874. X
  875. X  return i;
  876. X}
  877. X
  878. X/* Find the epsilon closure of a set of positions.  If any position of the set
  879. X   contains a symbol that matches the empty string in some context, replace
  880. X   that position with the elements of its follow labeled with an appropriate
  881. X   constraint.  Repeat exhaustively until no funny positions are left.
  882. X   S->elems must be large enough to hold the result. */
  883. Xepsclosure(s, r)
  884. X     _position_set *s;
  885. X     struct regexp *r;
  886. X{
  887. X  int i, j;
  888. X  int *visited;
  889. X  _position p, old;
  890. X
  891. X  MALLOC(visited, int, r->tindex);
  892. X  for (i = 0; i < r->tindex; ++i)
  893. X    visited[i] = 0;
  894. X
  895. X  for (i = 0; i < s->nelem; ++i)
  896. X    if (r->tokens[s->elems[i].index] >= _NOTCHAR
  897. X    && r->tokens[s->elems[i].index] != _BACKREF
  898. X    && r->tokens[s->elems[i].index] < _SET)
  899. X      {
  900. X    old = s->elems[i];
  901. X    p.constraint = old.constraint;
  902. X    delete(s->elems[i], s);
  903. X    if (visited[old.index])
  904. X      {
  905. X        --i;
  906. X        continue;
  907. X      }
  908. X    visited[old.index] = 1;
  909. X    switch (r->tokens[old.index])
  910. X      {
  911. X      case _BEGLINE:
  912. X        p.constraint &= _BEGLINE_CONSTRAINT;
  913. X        break;
  914. X      case _ENDLINE:
  915. X        p.constraint &= _ENDLINE_CONSTRAINT;
  916. X        break;
  917. X      case _BEGWORD:
  918. X        p.constraint &= _BEGWORD_CONSTRAINT;
  919. X        break;
  920. X      case _ENDWORD:
  921. X        p.constraint &= _ENDWORD_CONSTRAINT;
  922. X        break;
  923. X      case _LIMWORD:
  924. X        p.constraint &= _ENDWORD_CONSTRAINT;
  925. X        break;
  926. X      case _NOTLIMWORD:
  927. X        p.constraint &= _NOTLIMWORD_CONSTRAINT;
  928. X        break;
  929. X      }
  930. X    for (j = 0; j < r->follows[old.index].nelem; ++j)
  931. X      {
  932. X        p.index = r->follows[old.index].elems[j].index;
  933. X        insert(p, s);
  934. X      }
  935. X    /* Force rescan to start at the beginning. */
  936. X    i = -1;
  937. X      }
  938. X
  939. X  free(visited);
  940. X}
  941. X
  942. X/* Perform bottom-up analysis on the parse tree, computing various functions.
  943. X   Note that at this point, we're pretending constructs like \< are real
  944. X   characters rather than constraints on what can follow them.
  945. X
  946. X   Nullable:  A node is nullable if it is at the root of a regexp that can
  947. X   match the empty string.
  948. X   *  _EMPTY leaves are nullable.
  949. X   * No other leaf is nullable.
  950. X   * A _QMARK or _STAR node is nullable.
  951. X   * A _PLUS node is nullable if its argument is nullable.
  952. X   * A _CAT node is nullable if both its arguments are nullable.
  953. X   * An _OR node is nullable if either argument is nullable.
  954. X
  955. X   Firstpos:  The firstpos of a node is the set of positions (nonempty leaves)
  956. X   that could correspond to the first character of a string matching the
  957. X   regexp rooted at the given node.
  958. X   * _EMPTY leaves have empty firstpos.
  959. X   * The firstpos of a nonempty leaf is that leaf itself.
  960. X   * The firstpos of a _QMARK, _STAR, or _PLUS node is the firstpos of its
  961. X     argument.
  962. X   * The firstpos of a _CAT node is the firstpos of the left argument, union
  963. X     the firstpos of the right if the left argument is nullable.
  964. X   * The firstpos of an _OR node is the union of firstpos of each argument.
  965. X
  966. X   Lastpos:  The lastpos of a node is the set of positions that could
  967. X   correspond to the last character of a string matching the regexp at
  968. X   the given node.
  969. X   * _EMPTY leaves have empty lastpos.
  970. X   * The lastpos of a nonempty leaf is that leaf itself.
  971. X   * The lastpos of a _QMARK, _STAR, or _PLUS node is the lastpos of its
  972. X     argument.
  973. X   * The lastpos of a _CAT node is the lastpos of its right argument, union
  974. X     the lastpos of the left if the right argument is nullable.
  975. X   * The lastpos of an _OR node is the union of the lastpos of each argument.
  976. X
  977. X   Follow:  The follow of a position is the set of positions that could
  978. X   correspond to the character following a character matching the node in
  979. X   a string matching the regexp.  At this point we consider special symbols
  980. X   that match the empty string in some context to be just normal characters.
  981. X   Later, if we find that a special symbol is in a follow set, we will
  982. X   replace it with the elements of its follow, labeled with an appropriate
  983. X   constraint.
  984. X   * Every node in the firstpos of the argument of a _STAR or _PLUS node is in
  985. X     the follow of every node in the lastpos.
  986. X   * Every node in the firstpos of the second argument of a _CAT node is in
  987. X     the follow of every node in the lastpos of the first argument.
  988. X
  989. X   Because of the postfix representation of the parse tree, the depth-first
  990. X   analysis is conveniently done by a linear scan with the aid of a stack.
  991. X   Sets are stored as arrays of the elements, obeying a stack-like allocation
  992. X   scheme; the number of elements in each set deeper in the stack can be
  993. X   used to determine the address of a particular set's array. */
  994. Xvoid
  995. Xreganalyze(r, searchflag)
  996. X     struct regexp *r;
  997. X     int searchflag;
  998. X{
  999. X  int *nullable;        /* Nullable stack. */
  1000. X  int *nfirstpos;        /* Element count stack for firstpos sets. */
  1001. X  _position *firstpos;        /* Array where firstpos elements are stored. */
  1002. X  int *nlastpos;        /* Element count stack for lastpos sets. */
  1003. X  _position *lastpos;        /* Array where lastpos elements are stored. */
  1004. X  int *nalloc;            /* Sizes of arrays allocated to follow sets. */
  1005. X  _position_set tmp;        /* Temporary set for merging sets. */
  1006. X  _position_set merged;        /* Result of merging sets. */
  1007. X  int wants_newline;        /* True if some position wants newline info. */
  1008. X  int *o_nullable;
  1009. X  int *o_nfirst, *o_nlast;
  1010. X  _position *o_firstpos, *o_lastpos;
  1011. X  int i, j;
  1012. X  _position *pos;
  1013. X
  1014. X  r->searchflag = searchflag;
  1015. X
  1016. X  MALLOC(nullable, int, r->depth);
  1017. X  o_nullable = nullable;
  1018. X  MALLOC(nfirstpos, int, r->depth);
  1019. X  o_nfirst = nfirstpos;
  1020. X  MALLOC(firstpos, _position, r->nleaves);
  1021. X  o_firstpos = firstpos, firstpos += r->nleaves;
  1022. X  MALLOC(nlastpos, int, r->depth);
  1023. X  o_nlast = nlastpos;
  1024. X  MALLOC(lastpos, _position, r->nleaves);
  1025. X  o_lastpos = lastpos, lastpos += r->nleaves;
  1026. X  MALLOC(nalloc, int, r->tindex);
  1027. X  for (i = 0; i < r->tindex; ++i)
  1028. X    nalloc[i] = 0;
  1029. X  MALLOC(merged.elems, _position, r->nleaves);
  1030. X
  1031. X  CALLOC(r->follows, _position_set, r->tindex);
  1032. X
  1033. X  for (i = 0; i < r->tindex; ++i)
  1034. X    switch (r->tokens[i])
  1035. X      {
  1036. X      case _EMPTY:
  1037. X    /* The empty set is nullable. */
  1038. X    *nullable++ = 1;
  1039. X
  1040. X    /* The firstpos and lastpos of the empty leaf are both empty. */
  1041. X    *nfirstpos++ = *nlastpos++ = 0;
  1042. X    break;
  1043. X
  1044. X      case _STAR:
  1045. X      case _PLUS:
  1046. X    /* Every element in the firstpos of the argument is in the follow
  1047. X       of every element in the lastpos. */
  1048. X    tmp.nelem = nfirstpos[-1];
  1049. X    tmp.elems = firstpos;
  1050. X    pos = lastpos;
  1051. X    for (j = 0; j < nlastpos[-1]; ++j)
  1052. X      {
  1053. X        merge(&tmp, &r->follows[pos[j].index], &merged);
  1054. X        REALLOC_IF_NECESSARY(r->follows[pos[j].index].elems, _position,
  1055. X                 nalloc[pos[j].index], merged.nelem - 1);
  1056. X        copy(&merged, &r->follows[pos[j].index]);
  1057. X      }
  1058. X
  1059. X      case _QMARK:
  1060. X    /* A _QMARK or _STAR node is automatically nullable. */
  1061. X    if (r->tokens[i] != _PLUS)
  1062. X      nullable[-1] = 1;
  1063. X    break;
  1064. X
  1065. X      case _CAT:
  1066. X    /* Every element in the firstpos of the second argument is in the
  1067. X       follow of every element in the lastpos of the first argument. */
  1068. X    tmp.nelem = nfirstpos[-1];
  1069. X    tmp.elems = firstpos;
  1070. X    pos = lastpos + nlastpos[-1];
  1071. X    for (j = 0; j < nlastpos[-2]; ++j)
  1072. X      {
  1073. X        merge(&tmp, &r->follows[pos[j].index], &merged);
  1074. X        REALLOC_IF_NECESSARY(r->follows[pos[j].index].elems, _position,
  1075. X                 nalloc[pos[j].index], merged.nelem - 1);
  1076. X        copy(&merged, &r->follows[pos[j].index]);
  1077. X      }
  1078. X
  1079. X    /* The firstpos of a _CAT node is the firstpos of the first argument,
  1080. X       union that of the second argument if the first is nullable. */
  1081. X    if (nullable[-2])
  1082. X      nfirstpos[-2] += nfirstpos[-1];
  1083. X    else
  1084. X      firstpos += nfirstpos[-1];
  1085. X    --nfirstpos;
  1086. X
  1087. X    /* The lastpos of a _CAT node is the lastpos of the second argument,
  1088. X       union that of the first argument if the second is nullable. */
  1089. X    if (nullable[-1])
  1090. X      nlastpos[-2] += nlastpos[-1];
  1091. X    else
  1092. X      {
  1093. X        pos = lastpos + nlastpos[-2];
  1094. X        for (j = nlastpos[-1] - 1; j >= 0; --j)
  1095. X          pos[j] = lastpos[j];
  1096. X        lastpos += nlastpos[-2];
  1097. X        nlastpos[-2] = nlastpos[-1];
  1098. X      }
  1099. X    --nlastpos;
  1100. X
  1101. X    /* A _CAT node is nullable if both arguments are nullable. */
  1102. X    nullable[-2] = nullable[-1] && nullable[-2];
  1103. X    --nullable;
  1104. X    break;
  1105. X
  1106. X      case _OR:
  1107. X    /* The firstpos is the union of the firstpos of each argument. */
  1108. X    nfirstpos[-2] += nfirstpos[-1];
  1109. X    --nfirstpos;
  1110. X
  1111. X    /* The lastpos is the union of the lastpos of each argument. */
  1112. X    nlastpos[-2] += nlastpos[-1];
  1113. X    --nlastpos;
  1114. X
  1115. X    /* An _OR node is nullable if either argument is nullable. */
  1116. X    nullable[-2] = nullable[-1] || nullable[-2];
  1117. X    --nullable;
  1118. X    break;
  1119. X
  1120. X      default:
  1121. X    /* Anything else is a nonempty position.  (Note that special
  1122. X       constructs like \< are treated as nonempty strings here;
  1123. X       an "epsilon closure" effectively makes them nullable later.
  1124. X       Backreferences have to get a real position so we can detect
  1125. X       transitions on them later.  But they are nullable. */
  1126. X    *nullable++ = r->tokens[i] == _BACKREF;
  1127. X
  1128. X    /* This position is in its own firstpos and lastpos. */
  1129. X    *nfirstpos++ = *nlastpos++ = 1;
  1130. X    --firstpos, --lastpos;
  1131. X    firstpos->index = lastpos->index = i;
  1132. X    firstpos->constraint = lastpos->constraint = _NO_CONSTRAINT;
  1133. X
  1134. X    /* Allocate the follow set for this position. */
  1135. X    nalloc[i] = 1;
  1136. X    MALLOC(r->follows[i].elems, _position, nalloc[i]);
  1137. X    break;
  1138. X      }
  1139. X
  1140. X  /* For each follow set that is the follow set of a real position, replace
  1141. X     it with its epsilon closure. */
  1142. X  for (i = 0; i < r->tindex; ++i)
  1143. X    if (r->tokens[i] < _NOTCHAR || r->tokens[i] == _BACKREF
  1144. X    || r->tokens[i] >= _SET)
  1145. X      {
  1146. X    copy(&r->follows[i], &merged);
  1147. X    epsclosure(&merged, r);
  1148. X    REALLOC(r->follows[i].elems, _position, merged.nelem);
  1149. X    copy(&merged, &r->follows[i]);
  1150. X      }
  1151. X
  1152. X  /* Get the epsilon closure of the firstpos of the regexp.  The result will
  1153. X     be the set of positions of state 0. */
  1154. X  merged.nelem = 0;
  1155. X  for (i = 0; i < nfirstpos[-1]; ++i)
  1156. X    insert(firstpos[i], &merged);
  1157. X  epsclosure(&merged, r);
  1158. X
  1159. X  /* Check if any of the positions of state 0 will want newline context. */
  1160. X  wants_newline = 0;
  1161. X  for (i = 0; i < merged.nelem; ++i)
  1162. X    if (_PREV_NEWLINE_DEPENDENT(merged.elems[i].constraint))
  1163. X      wants_newline = 1;
  1164. X
  1165. X  /* Build the initial state. */
  1166. X  r->salloc = 1;
  1167. X  r->sindex = 0;
  1168. X  MALLOC(r->states, _dfa_state, r->salloc);
  1169. X  state_index(r, &merged, wants_newline, 0);
  1170. X
  1171. X  free(o_nullable);
  1172. X  free(o_nfirst);
  1173. X  free(o_firstpos);
  1174. X  free(o_nlast);
  1175. X  free(o_lastpos);
  1176. X  free(nalloc);
  1177. X  free(merged.elems);
  1178. X}
  1179. X
  1180. X/* Find, for each character, the transition out of state s of r, and store
  1181. X   it in the appropriate slot of trans.
  1182. X
  1183. X   We divide the positions of s into groups (positions can appear in more
  1184. X   than one group).  Each group is labeled with a set of characters that
  1185. X   every position in the group matches (taking into account, if necessary,
  1186. X   preceding context information of s).  For each group, find the union
  1187. X   of the its elements' follows.  This set is the set of positions of the
  1188. X   new state.  For each character in the group's label, set the transition
  1189. X   on this character to be to a state corresponding to the set's positions,
  1190. X   and its associated backward context information, if necessary.
  1191. X
  1192. X   If we are building a searching matcher, we include the positions of state
  1193. X   0 in every state.
  1194. X
  1195. X   The collection of groups is constructed by building an equivalence-class
  1196. X   partition of the positions of s.
  1197. X
  1198. X   For each position, find the set of characters C that it matches.  Eliminate
  1199. X   any characters from C that fail on grounds of backward context.
  1200. X
  1201. X   Search through the groups, looking for a group whose label L has nonempty
  1202. X   intersection with C.  If L - C is nonempty, create a new group labeled
  1203. X   L - C and having the same positions as the current group, and set L to
  1204. X   the intersection of L and C.  Insert the position in this group, set
  1205. X   C = C - L, and resume scanning.
  1206. X
  1207. X   If after comparing with every group there are characters remaining in C,
  1208. X   create a new group labeled with the characters of C and insert this
  1209. X   position in that group. */
  1210. Xvoid
  1211. Xregstate(s, r, trans)
  1212. X     int s;
  1213. X     struct regexp *r;
  1214. X     int trans[];
  1215. X{
  1216. X  _position_set grps[_NOTCHAR];    /* As many as will ever be needed. */
  1217. X  _charset labels[_NOTCHAR];    /* Labels corresponding to the groups. */
  1218. X  int ngrps = 0;        /* Number of groups actually used. */
  1219. X  _position pos;        /* Current position being considered. */
  1220. X  _charset matches;        /* Set of matching characters. */
  1221. X  int matchesf;            /* True if matches is nonempty. */
  1222. X  _charset intersect;        /* Intersection with some label set. */
  1223. X  int intersectf;        /* True if intersect is nonempty. */
  1224. X  _charset leftovers;        /* Stuff in the label that didn't match. */
  1225. X  int leftoversf;        /* True if leftovers is nonempty. */
  1226. X  static _charset letters;    /* Set of characters considered letters. */
  1227. X  static _charset newline;    /* Set of characters that aren't newline. */
  1228. X  _position_set follows;    /* Union of the follows of some group. */
  1229. X  _position_set tmp;        /* Temporary space for merging sets. */
  1230. X  int state;            /* New state. */
  1231. X  int wants_newline;        /* New state wants to know newline context. */
  1232. X  int state_newline;        /* New state on a newline transition. */
  1233. X  int wants_letter;        /* New state wants to know letter context. */
  1234. X  int state_letter;        /* New state on a letter transition. */
  1235. X  static initialized;        /* Flag for static initialization. */
  1236. X  int i, j, k;
  1237. X
  1238. X  /* Initialize the set of letters, if necessary. */
  1239. X  if (! initialized)
  1240. X    {
  1241. X      initialized = 1;
  1242. X      for (i = 0; i < _NOTCHAR; ++i)
  1243. X    if (ISALNUM(i))
  1244. X      setbit(i, letters);
  1245. X      setbit('\n', newline);
  1246. X    }
  1247. X
  1248. X  zeroset(matches);
  1249. X
  1250. X  for (i = 0; i < r->states[s].elems.nelem; ++i)
  1251. X    {
  1252. X      pos = r->states[s].elems.elems[i];
  1253. X      if (r->tokens[pos.index] >= 0 && r->tokens[pos.index] < _NOTCHAR)
  1254. X    setbit(r->tokens[pos.index], matches);
  1255. X      else if (r->tokens[pos.index] >= _SET)
  1256. X    copyset(r->charsets[r->tokens[pos.index] - _SET], matches);
  1257. X      else
  1258. X    continue;
  1259. X
  1260. X      /* Some characters may need to be climinated from matches because
  1261. X     they fail in the current context. */
  1262. X      if (pos.constraint != 0xff)
  1263. X    {
  1264. X      if (! _MATCHES_NEWLINE_CONTEXT(pos.constraint,
  1265. X                     r->states[s].newline, 1))
  1266. X        clrbit('\n', matches);
  1267. X      if (! _MATCHES_NEWLINE_CONTEXT(pos.constraint,
  1268. X                     r->states[s].newline, 0))
  1269. X        for (j = 0; j < _CHARSET_INTS; ++j)
  1270. X          matches[j] &= newline[j];
  1271. X      if (! _MATCHES_LETTER_CONTEXT(pos.constraint,
  1272. X                    r->states[s].letter, 1))
  1273. X        for (j = 0; j < _CHARSET_INTS; ++j)
  1274. X          matches[j] &= ~letters[j];
  1275. X      if (! _MATCHES_LETTER_CONTEXT(pos.constraint,
  1276. X                    r->states[s].letter, 0))
  1277. X        for (j = 0; j < _CHARSET_INTS; ++j)
  1278. X          matches[j] &= letters[j];
  1279. X
  1280. X      /* If there are no characters left, there's no point in going on. */
  1281. X      for (j = 0; j < _CHARSET_INTS && !matches[j]; ++j)
  1282. X        ;
  1283. X      if (j == _CHARSET_INTS)
  1284. X        continue;
  1285. X    }
  1286. X
  1287. X      for (j = 0; j < ngrps; ++j)
  1288. X    {
  1289. X      /* If matches contains a single character only, and the current
  1290. X         group's label doesn't contain that character, go on to the
  1291. X         next group. */
  1292. X      if (r->tokens[pos.index] >= 0 && r->tokens[pos.index] < _NOTCHAR
  1293. X          && !tstbit(r->tokens[pos.index], labels[j]))
  1294. X        continue;
  1295. X
  1296. X      /* Check if this group's label has a nonempty intersection with
  1297. X         matches. */
  1298. X      intersectf = 0;
  1299. X      for (k = 0; k < _CHARSET_INTS; ++k)
  1300. X        (intersect[k] = matches[k] & labels[j][k]) ? intersectf = 1 : 0;
  1301. X      if (! intersectf)
  1302. X        continue;
  1303. X
  1304. X      /* It does; now find the set differences both ways. */
  1305. X      leftoversf = matchesf = 0;
  1306. X      for (k = 0; k < _CHARSET_INTS; ++k)
  1307. X        {
  1308. X          /* Even an optimizing compiler can't know this for sure. */
  1309. X          int match = matches[k], label = labels[j][k];
  1310. X
  1311. X          (leftovers[k] = ~match & label) ? leftoversf = 1 : 0;
  1312. X          (matches[k] = match & ~label) ? matchesf = 1 : 0;
  1313. X        }
  1314. X
  1315. X      /* If there were leftovers, create a new group labeled with them. */
  1316. X      if (leftoversf)
  1317. X        {
  1318. X          copyset(leftovers, labels[ngrps]);
  1319. X          copyset(intersect, labels[j]);
  1320. X          MALLOC(grps[ngrps].elems, _position, r->nleaves);
  1321. X          copy(&grps[j], &grps[ngrps]);
  1322. X          ++ngrps;
  1323. X        }
  1324. X
  1325. X      /* Put the position in the current group.  Note that there is no
  1326. X         reason to call insert() here. */
  1327. X      grps[j].elems[grps[j].nelem++] = pos;
  1328. X
  1329. X      /* If every character matching the current position has been
  1330. X         accounted for, we're done. */
  1331. X      if (! matchesf)
  1332. X        break;
  1333. X    }
  1334. X
  1335. X      /* If we've passed the last group, and there are still characters
  1336. X     unaccounted for, then we'll have to create a new group. */
  1337. X      if (j == ngrps)
  1338. X    {
  1339. X      copyset(matches, labels[ngrps]);
  1340. X      zeroset(matches);
  1341. X      MALLOC(grps[ngrps].elems, _position, r->nleaves);
  1342. X      grps[ngrps].nelem = 1;
  1343. X      grps[ngrps].elems[0] = pos;
  1344. X      ++ngrps;
  1345. X    }
  1346. X    }
  1347. X
  1348. X  MALLOC(follows.elems, _position, r->nleaves);
  1349. X  MALLOC(tmp.elems, _position, r->nleaves);
  1350. X
  1351. X  /* If we are a searching matcher, the default transition is to a state
  1352. X     containing the positions of state 0, otherwise the default transition
  1353. X     is to fail miserably. */
  1354. X  if (r->searchflag)
  1355. X    {
  1356. X      wants_newline = 0;
  1357. X      wants_letter = 0;
  1358. X      for (i = 0; i < r->states[0].elems.nelem; ++i)
  1359. X    {
  1360. X      if (_PREV_NEWLINE_DEPENDENT(r->states[0].elems.elems[i].constraint))
  1361. X        wants_newline = 1;
  1362. X      if (_PREV_LETTER_DEPENDENT(r->states[0].elems.elems[i].constraint))
  1363. X        wants_letter = 1;
  1364. X    }
  1365. X      copy(&r->states[0].elems, &follows);
  1366. X      state = state_index(r, &follows, 0, 0);
  1367. X      if (wants_newline)
  1368. X    state_newline = state_index(r, &follows, 1, 0);
  1369. X      else
  1370. X    state_newline = state;
  1371. X      if (wants_letter)
  1372. X    state_letter = state_index(r, &follows, 0, 1);
  1373. X      else
  1374. X    state_letter = state;
  1375. X      for (i = 0; i < _NOTCHAR; ++i)
  1376. X    if (i == '\n')
  1377. X      trans[i] = state_newline;
  1378. X    else if (ISALNUM(i))
  1379. X      trans[i] = state_letter;
  1380. X    else
  1381. X      trans[i] = state;
  1382. X    }
  1383. X  else
  1384. X    for (i = 0; i < _NOTCHAR; ++i)
  1385. X      trans[i] = -1;
  1386. X
  1387. X  for (i = 0; i < ngrps; ++i)
  1388. X    {
  1389. X      follows.nelem = 0;
  1390. X
  1391. X      /* Find the union of the follows of the positions of the group.
  1392. X     This is a hideously inefficient loop.  Fix it someday. */
  1393. X      for (j = 0; j < grps[i].nelem; ++j)
  1394. X    for (k = 0; k < r->follows[grps[i].elems[j].index].nelem; ++k)
  1395. X      insert(r->follows[grps[i].elems[j].index].elems[k], &follows);
  1396. X
  1397. X      /* If we are building a searching matcher, throw in the positions
  1398. X     of state 0 as well. */
  1399. X      if (r->searchflag)
  1400. X    for (j = 0; j < r->states[0].elems.nelem; ++j)
  1401. X      insert(r->states[0].elems.elems[j], &follows);
  1402. X
  1403. X      /* Find out if the new state will want any context information. */
  1404. X      wants_newline = 0;
  1405. X      if (tstbit('\n', labels[i]))
  1406. X    for (j = 0; j < follows.nelem; ++j)
  1407. X      if (_PREV_NEWLINE_DEPENDENT(follows.elems[j].constraint))
  1408. X        wants_newline = 1;
  1409. X
  1410. X      wants_letter = 0;
  1411. X      for (j = 0; j < _CHARSET_INTS; ++j)
  1412. X    if (labels[i][j] & letters[j])
  1413. X      break;
  1414. X      if (j < _CHARSET_INTS)
  1415. X    for (j = 0; j < follows.nelem; ++j)
  1416. X      if (_PREV_LETTER_DEPENDENT(follows.elems[j].constraint))
  1417. X        wants_letter = 1;
  1418. X
  1419. X      /* Find the state(s) corresponding to the union of the follows. */
  1420. X      state = state_index(r, &follows, 0, 0);
  1421. X      if (wants_newline)
  1422. X    state_newline = state_index(r, &follows, 1, 0);
  1423. X      else
  1424. X    state_newline = state;
  1425. X      if (wants_letter)
  1426. X    state_letter = state_index(r, &follows, 0, 1);
  1427. X      else
  1428. X    state_letter = state;
  1429. X
  1430. X      /* Set the transitions for each character in the current label. */
  1431. X      for (j = 0; j < _CHARSET_INTS; ++j)
  1432. X    for (k = 0; k < INTBITS; ++k)
  1433. X      if (labels[i][j] & 1 << k)
  1434. X        {
  1435. X          int c = j * INTBITS + k;
  1436. X
  1437. X          if (c == '\n')
  1438. X        trans[c] = state_newline;
  1439. X          else if (ISALNUM(c))
  1440. X        trans[c] = state_letter;
  1441. X          else if (c < _NOTCHAR)
  1442. X        trans[c] = state;
  1443. X        }
  1444. X    }
  1445. X
  1446. X  for (i = 0; i < ngrps; ++i)
  1447. X    free(grps[i].elems);
  1448. X  free(follows.elems);
  1449. X  free(tmp.elems);
  1450. X}
  1451. X
  1452. X/* Some routines for manipulating a compiled regexp's transition tables.
  1453. X   Each state may or may not have a transition table; if it does, and it
  1454. X   is a non-accepting state, then r->trans[state] points to its table.
  1455. X   If it is an accepting state then r->fails[state] points to its table.
  1456. X   If it has no table at all, then r->trans[state] is NULL.
  1457. X   TODO: Improve this comment, get rid of the unnecessary redundancy. */
  1458. X
  1459. Xstatic void
  1460. Xbuild_state(s, r)
  1461. X     int s;
  1462. X     struct regexp *r;
  1463. X{
  1464. X  int *trans;            /* The new transition table. */
  1465. X  int i;
  1466. X
  1467. X  /* Set an upper limit on the number of transition tables that will ever
  1468. X     exist at once.  1024 is arbitrary.  The idea is that the frequently
  1469. X     used transition tables will be quickly rebuilt, whereas the ones that
  1470. X     were only needed once or twice will be cleared away. */
  1471. X  if (r->trcount >= 1024)
  1472. X    {
  1473. X      for (i = 0; i < r->tralloc; ++i)
  1474. X    if (r->trans[i])
  1475. X      {
  1476. X        free((ptr_t) r->trans[i]);
  1477. X        r->trans[i] = NULL;
  1478. X      }
  1479. X    else if (r->fails[i])
  1480. X      {
  1481. X        free((ptr_t) r->fails[i]);
  1482. X        r->fails[i] = NULL;
  1483. X      }
  1484. X      r->trcount = 0;
  1485. X    }
  1486. X
  1487. X  ++r->trcount;
  1488. X
  1489. X  /* Set up the success bits for this state. */
  1490. X  r->success[s] = 0;
  1491. X  if (ACCEPTS_IN_CONTEXT(r->states[s].newline, 1, r->states[s].letter, 0,
  1492. X      s, *r))
  1493. X    r->success[s] |= 4;
  1494. X  if (ACCEPTS_IN_CONTEXT(r->states[s].newline, 0, r->states[s].letter, 1,
  1495. X      s, *r))
  1496. X    r->success[s] |= 2;
  1497. X  if (ACCEPTS_IN_CONTEXT(r->states[s].newline, 0, r->states[s].letter, 0,
  1498. X      s, *r))
  1499. X    r->success[s] |= 1;
  1500. X
  1501. X  MALLOC(trans, int, _NOTCHAR);
  1502. X  regstate(s, r, trans);
  1503. X
  1504. X  /* Now go through the new transition table, and make sure that the trans
  1505. X     and fail arrays are allocated large enough to hold a pointer for the
  1506. X     largest state mentioned in the table. */
  1507. X  for (i = 0; i < _NOTCHAR; ++i)
  1508. X    if (trans[i] >= r->tralloc)
  1509. X      {
  1510. X    int oldalloc = r->tralloc;
  1511. X
  1512. X    while (trans[i] >= r->tralloc)
  1513. X      r->tralloc *= 2;
  1514. X    REALLOC(r->realtrans, int *, r->tralloc + 1);
  1515. X    r->trans = r->realtrans + 1;
  1516. X    REALLOC(r->fails, int *, r->tralloc);
  1517. X    REALLOC(r->success, int, r->tralloc);
  1518. X    REALLOC(r->newlines, int, r->tralloc);
  1519. X    while (oldalloc < r->tralloc)
  1520. X      {
  1521. X        r->trans[oldalloc] = NULL;
  1522. X        r->fails[oldalloc++] = NULL;
  1523. X      }
  1524. X      }
  1525. X
  1526. X  /* Keep the newline transition in a special place so we can use it as
  1527. X     a sentinel. */
  1528. X  r->newlines[s] = trans['\n'];
  1529. X  trans['\n'] = -1;
  1530. X
  1531. X  if (ACCEPTING(s, *r))
  1532. X    r->fails[s] = trans;
  1533. X  else
  1534. X    r->trans[s] = trans;
  1535. X}
  1536. X
  1537. Xstatic void
  1538. Xbuild_state_zero(r)
  1539. X     struct regexp *r;
  1540. X{
  1541. X  r->tralloc = 1;
  1542. X  r->trcount = 0;
  1543. X  CALLOC(r->realtrans, int *, r->tralloc + 1);
  1544. X  r->trans = r->realtrans + 1;
  1545. X  CALLOC(r->fails, int *, r->tralloc);
  1546. X  MALLOC(r->success, int, r->tralloc);
  1547. X  MALLOC(r->newlines, int, r->tralloc);
  1548. X  build_state(0, r);
  1549. X}
  1550. X
  1551. X/* Search through a buffer looking for a match to the given struct regexp.
  1552. X   Find the first occurrence of a string matching the regexp in the buffer,
  1553. X   and the shortest possible version thereof.  Return a pointer to the first
  1554. X   character after the match, or NULL if none is found.  Begin points to
  1555. X   the beginning of the buffer, and end points to the first character after
  1556. X   its end.  We store a newline in *end to act as a sentinel, so end had
  1557. X   better point somewhere valid.  Newline is a flag indicating whether to
  1558. X   allow newlines to be in the matching string.  If count is non-
  1559. X   NULL it points to a place we're supposed to increment every time we
  1560. X   see a newline.  Finally, if backref is non-NULL it points to a place
  1561. X   where we're supposed to store a 1 if backreferencing happened and the
  1562. X   match needs to be verified by a backtracking matcher.  Otherwise
  1563. X   we store a 0 in *backref. */
  1564. Xchar *
  1565. Xregexecute(r, begin, end, newline, count, backref)
  1566. X     struct regexp *r;
  1567. X     char *begin;
  1568. X     char *end;
  1569. X     int newline;
  1570. X     int *count;
  1571. X     int *backref;
  1572. X{
  1573. X  register s, s1, tmp;        /* Current state. */
  1574. X  register unsigned char *p;    /* Current input character. */
  1575. X  register **trans, *t;        /* Copy of r->trans so it can be optimized
  1576. X                   into a register. */
  1577. X  static sbit[_NOTCHAR];    /* Table for anding with r->success. */
  1578. X  static sbit_init;
  1579. X
  1580. X  if (! sbit_init)
  1581. X    {
  1582. X      int i;
  1583. X
  1584. X      sbit_init = 1;
  1585. X      for (i = 0; i < _NOTCHAR; ++i)
  1586. X    if (i == '\n')
  1587. X      sbit[i] = 4;
  1588. X    else if (ISALNUM(i))
  1589. X      sbit[i] = 2;
  1590. X    else
  1591. X      sbit[i] = 1;
  1592. X    }
  1593. X
  1594. X  if (! r->tralloc)
  1595. X    build_state_zero(r);
  1596. X
  1597. X  s = 0;
  1598. X  p = (unsigned char *) begin;
  1599. X  trans = r->trans;
  1600. X  *end = '\n';
  1601. X
  1602. X  for (;;)
  1603. X    {
  1604. X      /* The dreaded inner loop. */
  1605. X      if (t = trans[s])
  1606. X    do
  1607. X      {
  1608. X        s1 = t[*p++];
  1609. X        if (! (t = trans[s1]))
  1610. X          goto last_was_s;
  1611. X        s = t[*p++];
  1612. X      }
  1613. X        while (t = trans[s]);
  1614. X      goto last_was_s1;
  1615. X    last_was_s:
  1616. X      tmp = s, s = s1, s1 = tmp;
  1617. X    last_was_s1:
  1618. X
  1619. X      if (s >= 0 && p <= (unsigned char *) end && r->fails[s])
  1620. X    {
  1621. X      if (r->success[s] & sbit[*p])
  1622. X        {
  1623. X          if (backref)
  1624. X        if (r->states[s].backref)
  1625. X          *backref = 1;
  1626. X        else
  1627. X          *backref = 0;
  1628. X          return (char *) p;
  1629. X        }
  1630. X
  1631. X      s1 = s;
  1632. X      s = r->fails[s][*p++];
  1633. X      continue;
  1634. X    }
  1635. X
  1636. X      /* If the previous character was a newline, count it. */
  1637. X      if (count && (char *) p <= end && p[-1] == '\n')
  1638. X    ++*count;
  1639. X
  1640. X      /* Check if we've run off the end of the buffer. */
  1641. X      if ((char *) p >= end)
  1642. X    return NULL;
  1643. X
  1644. X      if (s >= 0)
  1645. X    {
  1646. X      build_state(s, r);
  1647. X      trans = r->trans;
  1648. X      continue;
  1649. X    }
  1650. X
  1651. X      if (p[-1] == '\n' && newline)
  1652. X    {
  1653. X      s = r->newlines[s1];
  1654. X      continue;
  1655. X    }
  1656. X
  1657. X      s = 0;
  1658. X    }
  1659. X}
  1660. X
  1661. X/* Initialize the components of a regexp that the other routines don't
  1662. X   initialize for themselves. */
  1663. Xvoid
  1664. Xreginit(r)
  1665. X     struct regexp *r;
  1666. X{
  1667. X  r->calloc = 1;
  1668. X  MALLOC(r->charsets, _charset, r->calloc);
  1669. X  r->cindex = 0;
  1670. X
  1671. X  r->talloc = 1;
  1672. X  MALLOC(r->tokens, _token, r->talloc);
  1673. X  r->tindex = r->depth = r->nleaves = r->nregexps = 0;
  1674. X
  1675. X  r->searchflag = 0;
  1676. X  r->tralloc = 0;
  1677. X}
  1678. X
  1679. X/* Parse and analyze a single string of the given length. */
  1680. Xvoid
  1681. Xregcompile(s, len, r, searchflag)
  1682. X     const char *s;
  1683. X     size_t len;
  1684. X     struct regexp *r;
  1685. X     int searchflag;
  1686. X{
  1687. X  if (case_fold)    /* dummy folding in service of regmust() */
  1688. X    {
  1689. X    static char *p;
  1690. X
  1691. X    case_fold = 0;
  1692. X    for (p = (char *)s; *p != 0; p++)
  1693. X        if (isupper((int)*p))
  1694. X            *p = tolower((int) *p);
  1695. X    reginit(r);
  1696. X    r->mustn = 0;
  1697. X    r->must[0] = '\0';
  1698. X    regparse(s, len, r);
  1699. X    regmust(r);
  1700. X        reganalyze(r, searchflag);
  1701. X    case_fold = 1;
  1702. X    reginit(r);
  1703. X    regparse(s, len, r);
  1704. X        reganalyze(r, searchflag);
  1705. X    }
  1706. X  else
  1707. X    {
  1708. X        reginit(r);
  1709. X        regparse(s, len, r);
  1710. X        regmust(r);
  1711. X        reganalyze(r, searchflag);
  1712. X    }
  1713. X}
  1714. X
  1715. X/* Free the storage held by the components of a regexp. */
  1716. Xvoid
  1717. Xregfree(r)
  1718. X     struct regexp *r;
  1719. X{
  1720. X  int i;
  1721. X
  1722. X  free((ptr_t) r->charsets);
  1723. X  free((ptr_t) r->tokens);
  1724. X  for (i = 0; i < r->sindex; ++i)
  1725. X    free((ptr_t) r->states[i].elems.elems);
  1726. X  free((ptr_t) r->states);
  1727. X  for (i = 0; i < r->tindex; ++i)
  1728. X    if (r->follows[i].elems)
  1729. X      free((ptr_t) r->follows[i].elems);
  1730. X  free((ptr_t) r->follows);
  1731. X  for (i = 0; i < r->tralloc; ++i)
  1732. X    if (r->trans[i])
  1733. X      free((ptr_t) r->trans[i]);
  1734. X    else if (r->fails[i])
  1735. X      free((ptr_t) r->fails[i]);
  1736. X  free((ptr_t) r->realtrans);
  1737. X  free((ptr_t) r->fails);
  1738. X  free((ptr_t) r->newlines);
  1739. X}
  1740. X
  1741. X/*
  1742. XHaving found the postfix representation of the regular expression,
  1743. Xtry to find a long sequence of characters that must appear in any line
  1744. Xcontaining the r.e.
  1745. XFinding a "longest" sequence is beyond the scope of this bagatelle;
  1746. Xwe take the easy way out and hope for the best.
  1747. X
  1748. XWe do a bottom-up calculation of several (possibly zero-length) sequences
  1749. Xof characters that must appear in matches of r.e.'s represented by trees
  1750. Xrooted at the nodes of the postfix representation:
  1751. X    sequences that must appear at the left of the match ("left")
  1752. X    sequences that must appear at the right of the match ("right")
  1753. X    sequences that must appear somewhere in the match ("in")
  1754. X    sequences that must constitute the match ("is")
  1755. XWhen we get to the root of the tree, we use its calculated "in" sequence
  1756. Xas our answer.  The sequence we find is returned in r->must (where "r" is
  1757. Xthe single argument passed to "regmust"); the length of the sequence is
  1758. Xreturned in r->mustn.
  1759. X
  1760. XThe sequences calculated for the various types of node (in pseudo ANSI c)
  1761. Xare shown below.  "p" is the operand of unary operators (and the left-hand
  1762. Xoperand of binary operators); "q" is the right-hand operand of binary operators.
  1763. X"ZERO" means "a zero-length sequence" below.
  1764. X
  1765. XType    left        right        is        in
  1766. X----    ----        -----        --        --
  1767. Xchar c    # c        # c        # c        # c
  1768. X
  1769. XSET    ZERO        ZERO        ZERO        ZERO
  1770. X
  1771. XSTAR    ZERO        ZERO        ZERO        ZERO
  1772. X
  1773. XQMARK    ZERO        ZERO        ZERO        ZERO
  1774. X
  1775. XPLUS    p->left        p->right    ZERO        ZERO
  1776. X
  1777. XCAT    (p->is==ZERO)?    (q->is==ZERO)?    (p->is!=ZERO &&    longest of
  1778. X    p->left :    q->right :    q->is!=ZERO) ?    p->in, q->in, or
  1779. X    p->is##q->left    p->right##q->is    p->is##q->is :    p->right##q->left
  1780. X                    ZERO
  1781. X
  1782. XOR    longest common    longest common    (do p->is and    (do p->in and
  1783. X    leading        trailing    q->is have same    q->in have same
  1784. X    (sub)sequence    (sub)sequence    length and    length and
  1785. X    of p->left    of p->right    content) ?    content) ?
  1786. X    and q->left    and q->right    p->is : NULL    p->in : NULL
  1787. X
  1788. XIf there's anything else we recognize in the tree, all four sequences get set
  1789. Xto zero-length sequences.  If there's something we don't recognize in the tree,
  1790. Xwe just return a zero-length sequence.
  1791. X
  1792. XAfter the above calculations are performed, three additional steps are taken:
  1793. X
  1794. X1.    If there's a non-zero-length "is" sequence, it replaces the
  1795. X    "left", "right", and "in" sequences.
  1796. X2.    If the "left" sequence is longer than the "in" sequence, it replaces
  1797. X    the "in" sequence.
  1798. X3.    If the "right" sequence is longer than the "in" sequence, it replaces
  1799. X    the "in" sequence.
  1800. X
  1801. XPossibilities:
  1802. X1.    Find the longest common (sub)sequence of p->in and q->in when doing
  1803. X    an OR node's "in" sequence?  Possibly effective, as in
  1804. X        egrep 'pepsi|epsilon'
  1805. X    but is it cheap and easy enough?
  1806. X2.    In replacing "in" sequences with "left" and "right" sequences, how
  1807. X    should ties be broken?
  1808. X3.    Switch to allocated memory, rather than relying on a defined MUST_MAX?
  1809. X*/
  1810. X
  1811. X#define TRUE    1
  1812. X#define FALSE    0
  1813. X
  1814. Xtypedef struct {
  1815. X    int    n;
  1816. X    char    p[MUST_MAX];
  1817. X} counted;
  1818. X
  1819. X#define initcounted(cp)    ((cp)->n = 0)
  1820. X
  1821. Xstatic void
  1822. Xcntcpy(top, fromp)
  1823. Xcounted *    top;
  1824. Xcounted *    fromp;
  1825. X{
  1826. X    register char *    fp;
  1827. X    register char *    tp;
  1828. X    register int    n;
  1829. X
  1830. X    fp = fromp->p;
  1831. X    tp = top->p;
  1832. X    n = fromp->n;
  1833. X    top->n = n;
  1834. X    while (n-- > 0)
  1835. X        *tp++ = *fp++;
  1836. X}
  1837. X
  1838. Xstatic void
  1839. Xcntcat(top, fromp)
  1840. Xcounted *    top;
  1841. Xcounted *    fromp;
  1842. X{
  1843. X    register char *    fp;
  1844. X    register char *    tp;
  1845. X    register int    n;
  1846. X
  1847. X    fp = fromp->p;
  1848. X    tp = top->p + top->n;
  1849. X    n = fromp->n;
  1850. X    top->n += n;
  1851. X    while (n-- > 0)
  1852. X        *tp++ = *fp++;
  1853. X}
  1854. X
  1855. Xstatic int
  1856. Xcntsame(acp, bcp)
  1857. Xcounted *    acp;
  1858. Xcounted *    bcp;
  1859. X{
  1860. X    register int    i;
  1861. X
  1862. X    if (acp->n != bcp->n)
  1863. X        return FALSE;
  1864. X    for (i = 0; i < acp->n; ++i)
  1865. X        if (acp->p[i] != bcp->p[i])
  1866. X            return FALSE;
  1867. X    return TRUE;
  1868. X}
  1869. X
  1870. X
  1871. Xtypedef struct {
  1872. X    counted    left;
  1873. X    counted    right;
  1874. X    counted    in;
  1875. X    counted    is;
  1876. X} must;
  1877. X
  1878. Xstatic void
  1879. Xinitmust(mp)
  1880. Xmust *    mp;
  1881. X{
  1882. X    initcounted(&mp->left);
  1883. X    initcounted(&mp->right);
  1884. X    initcounted(&mp->in);
  1885. X    initcounted(&mp->is);
  1886. X}
  1887. X
  1888. Xstatic void
  1889. Xregmust(r)
  1890. Xregister struct regexp *    r;
  1891. X{
  1892. X    must            musts[MUST_MAX];
  1893. X    register must *        mp;
  1894. X    counted            result;
  1895. X    register int        ri;
  1896. X    register int        i;
  1897. X    register _token        t;
  1898. X
  1899. X    reg->mustn = 0;
  1900. X    reg->must[0] = '\0';
  1901. X    if (reg->tindex > MUST_MAX)
  1902. X        return;
  1903. X    mp = musts;
  1904. X    initcounted(&result);
  1905. X    for (ri = 0; ri < reg->tindex; ++ri) {
  1906. X        switch (t = reg->tokens[ri]) {
  1907. X        case _ALLBEGLINE:
  1908. X        case _ALLENDLINE:
  1909. X        case _LPAREN:
  1910. X        case _RPAREN:
  1911. X            goto done;        /* "cannot happen" */
  1912. X        case _EMPTY:
  1913. X        case _BEGLINE:
  1914. X        case _ENDLINE:
  1915. X        case _BEGWORD:
  1916. X        case _ENDWORD:
  1917. X        case _LIMWORD:
  1918. X        case _NOTLIMWORD:
  1919. X        case _BACKREF:
  1920. X            initmust(mp);
  1921. X            break;
  1922. X        case _STAR:
  1923. X        case _QMARK:
  1924. X            if (mp <= musts)
  1925. X                goto done;    /* "cannot happen" */
  1926. X            --mp;
  1927. X            initmust(mp);
  1928. X            break;
  1929. X        case _OR:
  1930. X            if (mp < &musts[2])
  1931. X                goto done;    /* "cannot happen" */
  1932. X            {
  1933. X                register must *    lmp;
  1934. X                register must *    rmp;
  1935. X                register int    j, n;
  1936. X
  1937. X                rmp = --mp;
  1938. X                lmp = --mp;
  1939. X                /* Guaranteed to be.  Unlikely, but. . . */
  1940. X                if (!cntsame(&lmp->is, &rmp->is))
  1941. X                    initcounted(&lmp->is);
  1942. X                /* Left side--easy */
  1943. X                n = lmp->left.n;
  1944. X                if (n > rmp->left.n)
  1945. X                    n = rmp->left.n;
  1946. X                for (i = 0; i < n; ++i)
  1947. X                    if (lmp->left.p[i] != rmp->left.p[i])
  1948. X                        break;
  1949. X                lmp->left.n = i;
  1950. X                /* Right side */
  1951. X                n = lmp->right.n;
  1952. X                if (n > rmp->right.n)
  1953. X                    n = rmp->right.n;
  1954. X                for (i = 0; i < n; ++i)
  1955. X                    if (lmp->right.p[lmp->right.n-i-1] !=
  1956. X                        rmp->right.p[rmp->right.n-i-1])
  1957. X                        break;
  1958. X                for (j = 0; j < i; ++j)
  1959. X                    lmp->right.p[j] =
  1960. X                        lmp->right.p[(lmp->right.n -
  1961. X                            i) + j];
  1962. X                lmp->right.n = i;
  1963. X                /* Includes.  Unlikely, but. . . */
  1964. X                if (!cntsame(&lmp->in, &rmp->in))
  1965. X                    initcounted(&lmp->in);
  1966. X            }
  1967. X            break;
  1968. X        case _PLUS:
  1969. X            if (mp <= musts)
  1970. X                goto done;    /* "cannot happen" */
  1971. X            --mp;
  1972. X            initcounted(&mp->is);
  1973. X            break;
  1974. X        case _END:
  1975. X            if (mp != &musts[1])
  1976. X                goto done;    /* "cannot happen" */
  1977. X            result = musts[0].in;
  1978. X            goto done;
  1979. X        case _CAT:
  1980. X            if (mp < &musts[2])
  1981. X                goto done;    /* "cannot happen" */
  1982. X            {
  1983. X                must *    lmp;
  1984. X                must *    rmp;
  1985. X                must    new;
  1986. X                must *    nmp;
  1987. X                int    a, b, c;
  1988. X
  1989. X                rmp = --mp;
  1990. X                lmp = --mp;
  1991. X                nmp = &new;
  1992. X                initmust(nmp);
  1993. X                /* Left-hand */
  1994. X                cntcat(&nmp->left, &lmp->left);
  1995. X                if (lmp->is.n != 0)
  1996. X                    cntcat(&nmp->left, &rmp->left);
  1997. X                /* Right-hand */
  1998. X                if (rmp->is.n != 0)
  1999. X                    cntcat(&nmp->right, &lmp->right);
  2000. X                cntcat(&nmp->right, &rmp->right);
  2001. X                /* Guaranteed to be */
  2002. X                if (lmp->is.n != 0 && rmp->is.n != 0) {
  2003. X                    cntcat(&nmp->is, &lmp->is);
  2004. X                    cntcat(&nmp->is, &rmp->is);
  2005. X                }
  2006. X                /* Interior */
  2007. X                a = lmp->in.n;
  2008. X                b = rmp->in.n;
  2009. X                c = lmp->right.n + rmp->left.n;
  2010. X                if (a == 0 && b == 0 && c == 0) {
  2011. X                    /* nothing */
  2012. X                    ;
  2013. X                } else if (c > a && c > b) {
  2014. X                    cntcat(&nmp->in, &lmp->right);
  2015. X                    cntcat(&nmp->in, &rmp->left);
  2016. X                } else if (a > b) {
  2017. X                    cntcat(&nmp->in, &lmp->in);
  2018. X                } else {
  2019. X                    cntcat(&nmp->in, &rmp->in);
  2020. X                }
  2021. X                *mp = new;
  2022. X            }
  2023. X            break;
  2024. X        default:
  2025. X            if (t < _END) {
  2026. X                /* "cannot happen" */
  2027. X                goto done;
  2028. X            } else if (t >= _SET) {
  2029. X                /* easy enough */
  2030. X                initmust(mp);
  2031. X            } else {
  2032. X                /* plain character */
  2033. X                mp->left.p[0] = mp->right.p[0] =
  2034. X                    mp->in.p[0] = mp->is.p[0] = t;
  2035. X                mp->left.n = mp->right.n =
  2036. X                    mp->in.n = mp->is.n = 1;
  2037. X                break;
  2038. X            }
  2039. X            break;
  2040. X        }
  2041. X        /*
  2042. X        ** "Additional steps"
  2043. X        */
  2044. X        if (mp->is.n > 0) {
  2045. X            cntcpy(&mp->left, &mp->is);
  2046. X            cntcpy(&mp->right, &mp->is);
  2047. X            cntcpy(&mp->in, &mp->is);
  2048. X        }
  2049. X        if (mp->left.n > mp->in.n)
  2050. X            cntcpy(&mp->in, &mp->left);
  2051. X        if (mp->right.n > mp->in.n)
  2052. X            cntcpy(&mp->in, &mp->right);
  2053. X        ++mp;
  2054. X    }
  2055. Xdone:
  2056. X    reg->mustn = result.n;
  2057. X    for (i = 0; i < result.n; ++i)
  2058. X        reg->must[i] = result.p[i];
  2059. X}
  2060. END_OF_FILE
  2061. if test 54865 -ne `wc -c <'dfa.c'`; then
  2062.     echo shar: \"'dfa.c'\" unpacked with wrong size!
  2063. fi
  2064. # end of 'dfa.c'
  2065. fi
  2066. echo shar: End of shell archive.
  2067. exit 0
  2068.  
  2069.